import { Component, EventEmitter, Input, Output, OnInit, SecurityContext } from "@angular/core";
import { DomSanitizer, SafeUrl } from "@angular/platform-browser";

import { QiniuService } from "./qiniu.service";

@Component({
  selector: "img-upload",
  templateUrl: "imgupload.component.html",
  styleUrls: ["imgupload.component.less"]
})
export class ImgUploadComponent implements OnInit {
  @Input() title: string;
  @Output() onConfirmed = new EventEmitter<string>();

  constructor(private qiniuService: QiniuService, private sanitizer: DomSanitizer) { }
  previewImg: SafeUrl = "";
  imgObjUrl: string;
  imgObjFile: Object;
  sizeLimit = 150 * 1024;  // 150kb

  ngOnInit() { }

  uploadFile(data): void {
    if (data && data.srcElement.files[0]) {
      this.imgObjFile = data.srcElement.files[0];

      if (this.imgObjFile && this.imgObjFile['size'] > this.sizeLimit) {
        return alert('file is to large.');
      }
      this.imgObjUrl = URL.createObjectURL(this.imgObjFile);

      // this.previewImg = this.sanitizer.sanitize(SecurityContext.RESOURCE_URL, this.imgObjUrl);
      this.previewImg = this.sanitizer.bypassSecurityTrustResourceUrl(this.imgObjUrl);
    }
    console.info('upload file:', data, this.imgObjFile, this.imgObjUrl);
  }

  confirm(event: any) {
    this.qiniuService.upload(this.imgObjFile, (err, url) => {
      if (err) {
        console.error("upload failed: ", err);
      } else {
        console.info("upload success: ", url);
        this.imgObjUrl = url;
        this.onConfirmed.emit(url);
      }
    });
  }
}